import { defineStore } from 'pinia';

/**
 * 用户状态管理
 * 包含用户信息、认证状态等
 */
export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户基本信息
    userInfo: null as any,

    // 认证token
    token: '',

    // 登录状态
    isLoggedIn: false,

    // 用户权限
    permissions: [] as string[],

    // 用户偏好设置
    preferences: {
      theme: 'light',
      language: 'zh-CN',
      notifications: true,
    },
  }),

  getters: {
    // 获取用户名
    userName: state => state.userInfo?.name || '',

    // 获取用户头像
    userAvatar: state => state.userInfo?.avatar || '',

    // 检查是否有特定权限
    hasPermission: state => (permission: string) => {
      return state.permissions.includes(permission);
    },

    // 获取用户ID
    userId: state => state.userInfo?.id || '',
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo: any) {
      this.userInfo = userInfo;
      this.isLoggedIn = !!userInfo;
    },

    // 设置认证token
    setToken(token: string) {
      this.token = token;

      // 同时设置到cookie中
      const tokenCookie = useCookie('auth-token', {
        default: () => '',
        maxAge: 60 * 60 * 24 * 7, // 7天
        secure: true,
        sameSite: 'strict',
      });
      tokenCookie.value = token;
    },

    // 设置用户权限
    setPermissions(permissions: string[]) {
      this.permissions = permissions;
    },

    // 更新用户偏好设置
    updatePreferences(preferences: Partial<typeof this.preferences>) {
      this.preferences = { ...this.preferences, ...preferences };
    },

    // 登录
    async login(credentials: { username: string; password: string }) {
      try {
        // 这里调用登录API
        const { $http } = useNuxtApp();
        const response = await $http.post('/auth/login', credentials);

        if (response.data) {
          this.setToken(response.data.token);
          this.setUserInfo(response.data.user);
          this.setPermissions(response.data.permissions || []);
          return { success: true };
        }
      } catch (error) {
        console.error('登录失败:', error);
        return { success: false, error };
      }
    },

    // 登出
    async logout() {
      try {
        // 调用登出API
        const { $http } = useNuxtApp();
        await $http.post('/auth/logout');
      } catch (error) {
        console.error('登出API调用失败:', error);
      } finally {
        // 清除本地状态
        this.token = '';
        this.userInfo = null;
        this.isLoggedIn = false;
        this.permissions = [];

        // 清除cookie
        const tokenCookie = useCookie('auth-token');
        tokenCookie.value = null;

        // 跳转到登录页
        await navigateTo('/login');
      }
    },

    // 刷新用户信息
    async refreshUserInfo() {
      if (!this.token) return;

      try {
        const { $http } = useNuxtApp();
        const response = await $http.get('/user/profile');

        if (response.data) {
          this.setUserInfo(response.data);
        }
      } catch (error) {
        console.error('刷新用户信息失败:', error);
        // 如果token无效，执行登出
        if (error.code === 401) {
          await this.logout();
        }
      }
    },

    // 初始化用户状态（从cookie恢复）
    initializeAuth() {
      const tokenCookie = useCookie('auth-token');
      if (tokenCookie.value) {
        this.token = tokenCookie.value;
        // 可以在这里调用刷新用户信息
        this.refreshUserInfo();
      }
    },
  },
});
